package com.platform.modules.mch.task;

import com.platform.common.utils.Constant;
import com.platform.modules.dd.service.IDingTalkNotification;
import com.platform.modules.mall.entity.MallOrderEntity;
import com.platform.modules.mall.service.MallOrderService;
import com.platform.modules.mch.service.MchOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component("mchOrderTask")
public class MchOrderTask {

    @Resource
    private MallOrderService orderService;
    @Resource
    private MchOrderService mchOrderService;
    @Resource
    private IDingTalkNotification iDingTalkNotification;

    /**
     * 第三方商品下单
     */
    public void mchOrder() {
        List<MallOrderEntity> orderInfoList = orderService.lambdaQuery()
                .eq(MallOrderEntity::getPayStatus, Constant.PayStatus.YFK.getValue())
                .eq(MallOrderEntity::getOrderStatus, Constant.OrderStatus.YFK.getValue())
                .eq(MallOrderEntity::getOrderType, Constant.MCH_ORDER).list();
        if (orderInfoList.size() > 0) {
            log.info("第三方商品待下单数：" + orderInfoList.size());
            for (MallOrderEntity order : orderInfoList) {
                if(orderService.lambdaUpdate()
                        .set(MallOrderEntity::getOrderStatus,Constant.OrderStatus.YFK2.getValue())
                        .eq(MallOrderEntity::getOrderStatus,Constant.OrderStatus.YFK.getValue())
                        .eq(MallOrderEntity::getId,order.getId())
                        .update()){
                    try {
                        // 第三方平台下单
                        mchOrderService.orders(order,false);
                    }catch (Exception e){
                        // 此处需要通知管理员
                        // 日志打印
                        e.printStackTrace();
                        log.error("第三方商品下单失败！：   订单ID ：{}", order.getId());
                        // 标记发货出错
                        orderService.lambdaUpdate()
                                .set(MallOrderEntity::getShippingStatus, Constant.ShippingStatus.ERROR.getValue())
                                .eq(MallOrderEntity::getId, order.getId())
                                .update();
                        // 发通知提醒管理员
                        iDingTalkNotification.sentWorkNotification(Constant.MANAGER_NOTIFICATION, "通用系统 第三方商品下单失败", e.toString());
                    }
                }
            }
            log.info("------------------第三方商品下单完成-------------------");
        }
    }

}
